package fr.imag.ufrima.ima.project.ui.component;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.apache.log4j.Logger;

import fr.imag.ufrima.ima.project.ui.main.ImageProject;
import fr.imag.ufrima.ima.project.ui.utils.ImageFilter;
import fr.imag.ufrima.ima.project.ui.utils.Utils;

public class FileManager {
	private Logger logger = Logger.getLogger(getClass().getName());
	
	private ImageProject imageProject;
	private JFileChooser fileChooser;
	
	private ImageFilter allImages;
	private ImageFilter jpgImages;
	private ImageFilter gifImages;
	private ImageFilter bmpImages;
	private ImageFilter pngImages;
	
	public FileManager(ImageProject imageProject) {
		this.imageProject = imageProject;
		
		fileChooser = new JFileChooser();
		fileChooser.setAcceptAllFileFilterUsed(false);
		allImages = new ImageFilter(Utils.all);
		jpgImages = new ImageFilter(Utils.jpg);
		gifImages = new ImageFilter(Utils.gif);
		bmpImages = new ImageFilter(Utils.bmp);
		pngImages = new ImageFilter(Utils.png);

	}
	
	public File openFileDialog() {
		logger.debug(String.format("Open file dialog executing..."));
		
		File file = null;
		
		fileChooser.resetChoosableFileFilters();
		fileChooser.addChoosableFileFilter(allImages);

		int returnVal = fileChooser.showOpenDialog(this.imageProject);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			file = fileChooser.getSelectedFile();

			logger.debug(String.format("Selected file: %s", file.getAbsolutePath()));
		}
		return file;
	}
	
	public File saveFileDialog() {
		logger.debug(String.format("Save file dialog executing..."));
	
		File file = null;
		
		fileChooser.resetChoosableFileFilters();
		fileChooser.addChoosableFileFilter(jpgImages);
		fileChooser.addChoosableFileFilter(gifImages);
		fileChooser.addChoosableFileFilter(bmpImages);
		fileChooser.addChoosableFileFilter(pngImages);

		int returnVal = fileChooser.showSaveDialog(this.imageProject);

		if (returnVal == JFileChooser.APPROVE_OPTION) {

			file = fileChooser.getSelectedFile();

			logger.info(String.format("Selected file: %s", file.getAbsolutePath()));
		}
		return file;
	}
	
	public FileFilter getFileFilter() {
		return fileChooser.getFileFilter();
	}

}
